import React, { forwardRef } from 'react'
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import IconButton from '@material-ui/core/IconButton';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import MaterialTable from 'material-table';
import AddBox from '@material-ui/icons/AddBox';
import ArrowUpward from '@material-ui/icons/ArrowUpward';
import Check from '@material-ui/icons/Check';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';
import FileCopy from '@material-ui/icons/FileCopy';
import { Tip, loc_tag, cutTxt, is_empty } from '../../nui';
import { loc } from '../../local';

const tableIcons = () => {
    return {
        Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
        Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
        Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
        Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
        DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
        Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
        Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
        Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
        FirstPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("tb0")}</div>),
        LastPage: forwardRef((props, ref) =><div className="text-base" {...props} ref={ref}>{loc("tb1")}</div>),
        NextPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("tb2")}</div>),
        PreviousPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("tb3")}</div>),
        ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
        Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
        SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
        ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
        ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
    };
};

/* col: [
 *   {title: '序号', field: 'index'},
 *   {title: '工单号', field: 'sn', render: d => { return <div>xxxx</div> }},
 * ]
 *
 * row : [
 *   {index: '1', sn: "abc"},
 *   {index: '2', sn: "bcd"},
 * ]
 *
 * const editable = {
 *      onRowAdd: newData => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              setRow([...row, newData]);
 *              resolve();
 *          }, 200);
 *      }),
 *      onRowUpdate: (newData, oldData) => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              let data = [];
 *              data = row;
 *
 *              const f = data.find(d => d.sn === oldData.sn);
 *              if (f) {
 *                  f.sn = newData.sn;
 *                  f.des = newData.des;
 *              }
 *
 *              setRow(data);
 *              resolve();
 *          }, 200);
 *      }),
 *      onRowDelete: oldData => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              let data = [];
 *              for (let i = 0; i < row.length; i++) {
 *                  let d = row[i];
 *                  if (d.sn === oldData.sn) {
 *                      continue;
 *                  }
 *
 *                  data.push(d);
 *              }
 *
 *              setRow(data);
 *              resolve();
 *          }, 200);
 *      }),
 *  };
 *
 *  hcsv: (columns, data) => {}
*/
const MaTable = ({
    col,
    row,
    hselect,
    hclick,
    hcsv,
    fn,
    detail,
    actions,
    exbt=true,
    paging=true,
    page=5,
    curpage=0,
    title="",
    opt={},
    search=true,
    sort=true,
    parent,
    pageopt=[5, 6, 7],
    editable,
}) => {
    if (is_empty(col)) {
        return null;
    }

    let filename = "export";
    if (fn) {
        filename = fn + "_" + loc_tag();
    }

    const hSelectionChange = (v) => {
        if (hselect) {
            hselect(v);
        }
    };

    const hRowClick = (e, v) => {
        if (hclick) {
            hclick(v);
        }
    };

    const expBt = () => {
        if (exbt) {
            return {
                csv: exbt,
                pdf: false,
            };
        }

        return false;
    };

    const getRow = () => {
        if (is_empty(row)) {
            return [];
        }

        return row;
    };

    return (
        <MaterialTable
            detailPanel={detail}
            icons={tableIcons()}
            title={title}
            localization={{
                pagination: {
                    labelDisplayedRows: `${loc("tb4")} {from}-{to} , ${loc("tb5")} {count}`,
                    labelRowsSelect: loc("h"),
                    firstAriaLabel: loc("tb6"),
                    firstTooltip: loc("tb6"),
                    previousAriaLabel: loc("tb7"),
                    previousTooltip: loc("tb7"),
                    nextAriaLabel: loc("tb8"),
                    nextTooltip: loc("tb8"),
                    lastAriaLabel: loc("tb9"),
                    lastTooltip: loc("tb9"),
                },
                body: {
                    emptyDataSourceMessage: "",
                    addTooltip: loc("tj"),
                    deleteTooltip: loc("sc"),
                    editTooltip: loc("bj"),
                    editRow: {
                        deleteText: loc("tb10"),
                        cancelTooltip: loc("qxi"),
                        saveTooltip: loc("qd"),
                    }
                },
                header: {
                    actions: "",
                },
                toolbar: {
                    searchTooltip: loc("zjgs"),
                    searchPlaceholder: loc("zjgs"),
                    exportTitle: loc("dc"),
                    exportAriaLabel: loc("dc"),
                    exportCSVName: loc("dc") + " CSV",
                    nRowsSelected: `${loc("tb11")} {0} ${loc("h")}`,
                }
            }}
            options={{
                draggable: false,
                search: search,
                paging: paging,
                showTitle: title ? true : false,
                sorting: sort,
                exportAllData: true,
                exportButton: expBt(),
                exportFileName: filename,
                exportCsv: hcsv,
                pageSize: page,
                initialPage: curpage,
                pageSizeOptions: pageopt,
                ...opt
            }}
            onSelectionChange={hSelectionChange}
            onRowClick={hRowClick}
            columns={col}
            data={getRow()}
            actions={actions}
            parentChildData={parent}
            editable={editable}
        />
    );
};

const col_text = (label) => {
    if (label === undefined || label === null) {
        return null;
    }

    const MAX_W = 19;

    label += "";

    if (label.length <= MAX_W) {
        return <div>{label}</div>;
    }

    const t = cutTxt(label, MAX_W, 6);

    const Label = () => {
        return (
            <div>
                <CopyToClipboard text={label}>
                    <IconButton className="content-start m-0">
                        <FileCopy style={{ color: "white", margin: 1 }}/>
                    </IconButton>
                </CopyToClipboard>
                <div className="mt-2 flex-wrap" id="tplabel">{label}</div>
            </div>
        );
    };

    return (
        <Tip title={<Label/>} pos="bottom">
            <div>{t}</div>
        </Tip>
    );
};

/*
 * head: ["c1", "c2", "c3"]
 * row: [
 *      ["r1", "r2", "r3"],
 *      ["r11", "r12", "r13"],
 * ]
*/
const Stable = ({ head, row, k="t", cur, cut=false}) => {
    const data_head = () => {
        if (is_empty(head)) {
            return null;
        }

        return head.map((d, i) => <TableCell key={`${k}h${i}`}>{d}</TableCell>);
    };

    const get_val = (val) => {
        if (!val || val === "null") {
            return "";
        }

        if (cut) {
            return col_text(val, 40);
        }

        return val;
    };

    const data_row = () => {
        if (is_empty(row)) {
            return null;
        }

        let len = 999999;
        if (!is_empty(head)) {
            len = head.length;
        }

        let ret = [];
        row.forEach((d, i) => {
            if (is_empty(d)) {
                return;
            }

            let tmp = [];
            for (let j = 0; j < d.length && j < len; j++) {
                const t = d[j];
                tmp.push(<TableCell key={`${k}j${j}${i}`}>{get_val(t)}</TableCell>);
            }

            ret.push(<TableRow style={{ background: `${cur}` === d[0] ? "#BEE3F8" : "white" }} key={`${k}r${i}`}>{tmp}</TableRow>);
        });

        return ret;
    };

    return (
        <Table>
            <TableHead>
                <TableRow>
                    {data_head()}
                </TableRow>
            </TableHead>
            <TableBody>
                {data_row()}
            </TableBody>
        </Table>
    );
};

/* col: [
 *   {title: '序号', field: 'index'},
 *   {title: '工单号', field: 'sn'},
 * ]
 *
 * row : [
 *   {index: '1', sn: "abc"},
 *   {index: '2', sn: "bcd"},
 * ]
*/
const MaSmall = ({ col, row, paging=true, page=10, opt={}, curpage=0, toolbar=false, title=null, hselect }) => <MaTable
    col={col}
    row={row}
    paging={paging}
    exbt={false}
    page={page}
    curpage={curpage}
    title={title}
    opt={{
        padding: "dense",
        toolbar: toolbar,
        ...opt
    }}
    search={false}
    sort={false}
    hselect={hselect}
    pageopt={[page]}/>;

const cut_col = (d, k) => col_text(d[k]);

export {MaSmall, Stable, col_text, cut_col, MaTable};
